package com.example.trb.controller.word;


import com.deepoove.poi.config.Configure;
import com.example.trb.entity.User;
import com.example.trb.service.review.ReviewFormService;
import com.example.trb.util.result.CommonResult;
import com.example.trb.util.result.SysReturnCode;
import com.example.trb.util.word.WordUtil;
import com.example.trb.vo.ReviewFormVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
public class WordController {
    @Value(("${word.template}"))
    String templatePath;

    @Autowired
    ReviewFormService rfService;
    @Value("${session_user}")
    String userKey;

    static final int bufferSize = 1024;

    @GetMapping("/download/form")
    public void wordDownload(
            @RequestParam("id") Integer formId,
            HttpServletResponse response,
            HttpSession session
    ) throws IOException {
        ReviewFormVO reform = rfService.getReviewFormById(formId);

        System.out.println(reform.toString());
        if (!reform.getReviewForm().getStatus().equals("未完成")){
            //设置生成文件的名字
            String filename = "评审表";
            filename = URLEncoder.encode(filename,"UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=\""+ filename +".docx");
            ServletOutputStream sos = response.getOutputStream();

            Map<String,Object> map = new HashMap<>();
            //将信息添加到hashMap中
            WordUtil.AddInfo_User(reform,map);
            WordUtil.AddSummery(reform,map);
            Configure config =  WordUtil.TableLoop(reform,map);

            //填充并下载
            WordUtil.download(sos, templatePath,map,config);
        }
    }
}
